#!/usr/bin/env python
import os
import shutil
import sys
import subprocess
import argparse
from stdeb.downloader import myprint, get_source_tarball
import tempfile


def main():
    parser = argparse.ArgumentParser(
        usage='%(prog)s PACKAGE_NAME [options] [py2dsc-deb options]')
    parser.add_argument(
        '--verbose', type=int,
        help='verbosity level',
        default=0)
    parser.add_argument(
        '--release', type=str,
        help='specify a particular release',
        default=None)
    parser.add_argument(
        '--keep', action='store_true',
        default=False,
        help='do not remove temporary files')
    parser.add_argument(
        '--allow-unsafe-download', action='store_true',
        default=False,
        help='allow unsafe downloads')
    (options, args) = parser.parse_known_args()

    if os.geteuid() != 0:
        myprint(
            '%s must be run as root' % os.path.basename(sys.argv[0]),
            file=sys.stderr)
        sys.exit(1)

    if len(args) < 1:
        myprint('need exactly one PACKAGE_NAME', file=sys.stderr)
        parser.print_help()
        sys.exit(1)

    package_name = args[0]
    py2dsc_args = args[1:]
    if package_name.startswith('-'):
        myprint('PACKAGE_NAME must be first argument', file=sys.stderr)
        parser.print_help()
        sys.exit(1)

    orig_dir = os.path.abspath(os.curdir)
    tmpdir = os.path.abspath(tempfile.mkdtemp())
    try:
        if options.verbose >= 2:
            myprint('downloading to %s' % tmpdir)
        os.chdir(tmpdir)
        tarball_fname = get_source_tarball(
            package_name, verbose=options.verbose,
            release=options.release,
            allow_unsafe_download=options.allow_unsafe_download)

        cmd = ' '.join(['py2dsc-deb'] + py2dsc_args + [tarball_fname])
        if options.verbose >= 2:
            myprint('executing: %s' % cmd)
        subprocess.check_call(cmd, shell=True)

        os.chdir('deb_dist')
        cmd = 'dpkg -i *.deb'
        if options.verbose >= 2:
            myprint('executing: %s' % cmd)
        subprocess.check_call(cmd, shell=True)

    finally:
        os.chdir(orig_dir)
        if not options.keep:
            shutil.rmtree(tmpdir)


if __name__ == '__main__':
    main()
